package com.cms.cinema.query;

import com.cms.cinema.config.QueryConfig;
import com.cms.cinema.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Timer;
import java.util.Vector;
import java.util.concurrent.*;

/**
 * Query
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-24 10:29
 * @blame Team
 */
@Slf4j
@Component
public class Query {

    private static final Timer WRITER_TIMER = new Timer();
    public static int totalCount = 0;
    public static long s = 0L;
    public static CountDownLatch THREAD_LATCH;
    public static Vector<String> ipVector = new Vector<>();
    public static Vector<String> outVector = new Vector<>();
    public WriterTask writerTask;

    @Resource
    QueryConfig queryConfig;

    public void run() {
        try {
            s = Instant.now().toEpochMilli();
            writerTask = new WriterTask(queryConfig);

            log.info("使用线程池数量: {}", queryConfig.getThreadCount());
            THREAD_LATCH = new CountDownLatch(queryConfig.getThreadCount());

            // 读取IP列表
            ipVector = FileUtils.fileLineReader(queryConfig.getIpFileAbsoluteName());
            // ipVector.add("192.168.102.213");
            totalCount = ipVector.size();
            log.info("读取IP行数: {}", ipVector.size());

            //执行查询
            ExecutorService executorService = Executors.newFixedThreadPool(queryConfig.getThreadCount());
            for(int i = 1; i <= queryConfig.getThreadCount(); i++) {
                executorService.execute(new QuerySql(queryConfig, THREAD_LATCH));
            }
            executorService.shutdown();
            WRITER_TIMER.schedule(writerTask, 10000L, 10000L);
            THREAD_LATCH.await();
            WRITER_TIMER.cancel();
        }catch (Exception ex){
            log.error("", ex);
        }finally {
            writerTask.run();
            log.info("运行完成(query done).");
        }
    }
}
